<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CheckPermission
{
    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $admin = auth('admin')->user();
        if ( $admin->id === 1 ) return $next($request);

        $route = $request->route()->getAction();
        // $action = substr($route['controller'],21);
        $action = $route['controller'];
        $where['permissions.action'] = $action;
        $check_result = DB::table('permissions')
            ->join('role_has_menu_permissions', 'role_has_menu_permissions.id', '=', 'permissions.id')
            ->join('roles', 'roles.id', '=', 'role_has_menu_permissions.role_id')
            ->join('admin_has_roles', 'admin_has_roles.role_id', '=', 'roles.id')
            ->join('admins', 'admins.id', '=', 'admin_has_roles.admin_id')
            ->where('permissions.action', $action)
            ->where('role_has_menu_permissions.type', 1)
            ->where('admins.id', $admin->id)
            ->first();
        if ( empty($check_result) ) {
            return response()->json([
                'message' => '没有权限'
            ], 403);
        }
        return $next($request);
    }
}
